import React, { useEffect } from "react";
import NavBarAgain from "../components/NavBarAgain";
import { SwipeAction, Toast } from "antd-mobile";
import NewsItem from "../components/NewsItem";
import SKeleteAgain from "../components/SkeletonAgain";
import { connect } from "react-redux";
import action from "../store/action";
import "./Store.less";
import api from "../api";

export default connect(
  (state) => state.store,
  action.store
)(function Store(props) {
  let { list: storeList, queryStoreListAsync, removeStoreListById } = props;
  useEffect(() => {
    // 如果redux中没有收藏列表。
    if (!storeList) queryStoreListAsync();
  }, []);

  const handleRemove = async (id) => {
    try {
      let { code } = await api.storeRemove(id);
      if (+code !== 0) {
        Toast.show({
          icon: "fail",
          content: "移除失败",
        });
        return;
      }
      Toast.show({
        icon: "success",
        content: "移除成功",
      });
      removeStoreListById(id);
    } catch (_) {}
  };
  return (
    <div className="store-box">
      <NavBarAgain title="个人中心" />
      {storeList ? (
        <div className="box">
          {storeList.map((item) => {
            let { news, id } = item;
            return (
              <SwipeAction
                key={id}
                rightActions={[
                  {
                    key: "delete",
                    text: "删除",
                    color: "danger",
                    onClick: () => {
                      handleRemove(id);
                    },
                  },
                ]}
              >
                <NewsItem info={news}></NewsItem>
              </SwipeAction>
            );
          })}
        </div>
      ) : (
        <SKeleteAgain />
      )}
    </div>
  );
});
